package com.whf.android.jar.web.news;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.text.Html;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.whf.android.jar.app.Latte;
import com.whf.android.jar.net.gson.HttpGsonUtils;
import com.whf.android.jar.popup.listener.OnClickDecisionListener;
import com.whf.android.jar.util.log.LatteLogger;
import com.whf.android.jar.web.utils.HtmlUtils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.Map;

/**
 * 富文本适配
 *
 * @author lzl
 * @version 1.0
 */
public class NewsWebView extends WebView {

    private OnClickDecisionListener mClickListener = null;

    public NewsWebView(Context context) {
        super(context);
    }

    public NewsWebView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    /*** 富文本适配*/
    @SuppressLint("SetJavaScriptEnabled")
    public void setNewContent(String htmlText) {
        if (ObjectUtils.isEmpty(htmlText)) {
            return;
        }
        try {
            getSettings().setUserAgentString("latte");
            getSettings().setAllowFileAccess(true);
            getSettings().setAllowFileAccessFromFileURLs(true);
            getSettings().setJavaScriptEnabled(true);
            getSettings().setBuiltInZoomControls(true);
            getSettings().setDisplayZoomControls(false);
            // 支持缩放
            getSettings().setSupportZoom(true);

            //禁止上下左右滚动(不显示滚动条)
            setScrollContainer(false);
            setVerticalScrollBarEnabled(false);
            setHorizontalScrollBarEnabled(false);


            //取消滚动条白边效果
            setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
            getSettings().setDefaultTextEncodingName("UTF-8");
            getSettings().setDatabaseEnabled(true);

            getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);//设置缓存模式

            getSettings().setBlockNetworkImage(false);
            getSettings().setBlockNetworkLoads(false);
            getSettings().setMixedContentMode(WebSettings
                    .MIXED_CONTENT_ALWAYS_ALLOW);  //注意安卓5.0以上的权限

            Document docImg = Jsoup.parse(htmlText);
            Elements elementImg = docImg.getElementsByTag("img");
            for (Element element : elementImg) {
                if (element != null && element.toString().length() > 0) {
                    element.attr("width", "100%").attr("height", "auto");
                }
            }

            Document doc = Jsoup.parse(docImg.toString());

            Elements elementTab = doc.getElementsByTag("table");
            for (Element element : elementTab) {
                if (element != null && element.toString().length() > 0) {
                    element.attr("width", "100%").attr("height", "auto");
                }
            }

            //设置富文本
            loadDataWithBaseURL(null, doc.toString(), "text/html", "UTF-8", null);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 转义字符 &lt； &gt； 等等
     */
    @NonNull
    private String toHtml(String content) {
        if (ObjectUtils.isEmpty(content)) {
            return "";
        }
        return content.replace("&nbsp;", " ")
                .replace("&lt;", "<")
                .replace("&gt;", ">")
                .replace("&quot;", "\"")
                .replace("&apos;", "'")
                .replace("&#39;", "'")
                .replace("&amp;", "&")
                .replace("&cent;", "分")
                .replace("&pound;", "镑");
    }

    /***
     * 热力图等。
     * @param htmlText:file:///android_asset/index.html#/mapNetwork
     *                或者 https://gis.shzgx.com/h5/#/mapNetwork
     */
    @SuppressLint("SetJavaScriptEnabled")
    public void loadContent(String htmlText) {
        htmlText = toHtml(htmlText);
        if (ObjectUtils.isEmpty(htmlText)) {
            return;
        }
        if (htmlText.contains("text-indent:2em;") || htmlText.contains("text-indent: 2em;") ||
                htmlText.contains("<figure class=\"image\">")) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                htmlText = Html.fromHtml(htmlText, Html.FROM_HTML_MODE_LEGACY).toString();
            }
        }
        try {
            getSettings().setJavaScriptEnabled(true);
            getSettings().setBuiltInZoomControls(true);
            getSettings().setDisplayZoomControls(false);
            // 支持缩放
            getSettings().setSupportZoom(true);
            getSettings().setDomStorageEnabled(true);
            getSettings().setAllowFileAccess(true);
            getSettings().setAllowFileAccessFromFileURLs(true);
            getSettings().setAllowUniversalAccessFromFileURLs(true);
            getSettings().setAppCacheEnabled(true);
            getSettings().setAllowContentAccess(true);
            getSettings().setDefaultTextEncodingName("utf-8");//文本编码
            getSettings().setDatabaseEnabled(true);
            getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);

            //取消滚动条白边效果
            setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
            getSettings().setBlockNetworkImage(false);
            getSettings().setBlockNetworkLoads(false);
            getSettings().setMixedContentMode(WebSettings
                    .MIXED_CONTENT_ALWAYS_ALLOW);  //注意安卓5.0以上的权限
            addJavascriptInterface(this, "android");
            loadUrl(htmlText);


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setOnClickListener(OnClickDecisionListener listener) {
        this.mClickListener = listener;
    }

    @JavascriptInterface
    public void back(String o) {
        LatteLogger.i("点击事件: " + o);
        if (TextUtils.isEmpty(o)) {
            ToastUtils.showShort("暂无详细信息!");
            return;
        }
        Map<String, Object> map = HttpGsonUtils.fromJson(o);
        if (map == null || map.size() == 0) {
            ToastUtils.showShort("暂无详细信息!");
            return;
        }
        if (mClickListener != null) {
            mClickListener.onConfirm(map);
        }
    }

    public void addLayer(final String javascript) {
        Latte.getHandler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //延迟0.6秒加载数据.
                loadUrl("javascript:" + javascript);
            }
        }, 600);
    }

}
